import { TargetState } from "framework/FSM/DecisionTree/DecisionTargetState";
import { ITransition } from ".";
import { DecisionNode } from "..";
import { State } from "../AState";
import { DecisionTreeNode } from "../DecisionTree/DecisionTreeNode";


export class DecisionTreeTransition<T extends IStateArg = IStateArg> implements ITransition<T>
{
    private decisionTargetState?:TargetState<State>;
    private decisionTreeRoot!:DecisionNode;
    private origin!:State;
    constructor( condition:DecisionTreeNode )
    {

        this.decisionTreeRoot = condition;

    }
    public setOrigin(origin:State)
    {
        if(!origin)
        {
            throw new Error("origin is undefined");
        }
        this.origin = origin;
    }
    public getActions(arg:T):Action[]
    {
        //return [];
        if(this.decisionTargetState)
        {
            return this.decisionTargetState.getActions(arg);
        }
        else
        {
            return [];
        }
    }

    public getTargetState(): State|undefined
    {
        if(this.decisionTargetState)
        {
            return this.decisionTargetState.getTargetState();
        }
        else
        {
            return undefined;
        }
    }
    public getLevel():number
    {
        const targetstate = this.getTargetState();
        if(targetstate)
        {
            return this.origin.getLevel() - targetstate.getLevel();
        }
        else
        {
            throw new Error(`[Transition]_"targetstate->未定义`);
        }

    }
    public isTriggered(arg:T): boolean
    {
        this.decisionTargetState = this.makeDecision(arg,this.decisionTreeRoot);
        return this.decisionTargetState !== undefined;
    }

    protected makeDecision(arg:T,node?:DecisionNode): TargetState|undefined
    {
        if(!node || node.type==1)
        {
            return node as TargetState|undefined;
        }
        else
        {
            const brenode = node.makeDecision(arg);
            if(brenode)
            {
                return this.makeDecision(arg,brenode);
            }
            return undefined

        }
    }
}
